import NProgress from 'nprogress';
import pinia from '@/store';
import { useUserInfo } from '@/store/user';
import { usePermissionStore } from '@/store/permission';
import { storeToRefs } from 'pinia';
import { dynamicRoutes, staticRoutes, notFoundAndNoPower } from './router';
import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router';

export const router = createRouter({
  history: createWebHistory(),
  routes: [...staticRoutes, ...notFoundAndNoPower],
});

/**
 * 判断路由 `meta.roles` 中是否包含当前登录用户权限字段
 * @param role 用户权限标识
 * @param route 当前循环时的路由项
 * @returns 返回对比后有权限的路由项
 */
export function hasRoles(role: string[], route: any) {
  const containsValue = role.some((value) => route.meta.roles.includes(value));
  return route.meta.roles && containsValue;
}

/**
 * 递归过滤没有权限的路由
 * @description 用于左侧菜单、横向菜单的显示
 * @param routes 原始路由表
 * @returns 返回过滤后的路由表
 */
export function setFilterRolesMenu(routes: RouteRecordRaw[]): RouteRecordRaw[] {
  const userStore = useUserInfo();
  const { userInfos } = storeToRefs(userStore);

  // 确保 userInfos 和 menus 存在
  if (!userInfos.value || !userInfos.value.menus) {
    return [];
  }

  const { menus } = userInfos.value;

  return routes.reduce<RouteRecordRaw[]>((menu, route) => {
    // 检查当前路由是否有权限
    if (hasRoles(menus, route)) {
      const filteredRoute: RouteRecordRaw = { ...route };
      if (route.children && Array.isArray(route.children)) {
        filteredRoute.children = setFilterRolesMenu(route.children);
      } else {
        filteredRoute.children = undefined;
      }
      menu.push(filteredRoute);
    }
    return menu;
  }, []);
}

// 添加动态路由
export function setAddRoute() {
  const permissionStore = usePermissionStore(pinia);
  const filterRoute = setFilterRolesMenu(dynamicRoutes[0].children!);
  const updateRoutes = { ...dynamicRoutes[0], children: filterRoute };
  router.addRoute(updateRoutes);
  permissionStore.setRoutesList(filterRoute);
  return updateRoutes;
}

//路由加载前
router.beforeEach(async (to, _, next) => {
  NProgress.configure({ showSpinner: false });
  NProgress.start();

  const userStore = useUserInfo();
  const permissionStore = usePermissionStore(pinia);

  const { token } = storeToRefs(userStore);
  const { layoutLeftRoutes } = storeToRefs(permissionStore);

  if (to.path === '/login') {
    next();
  } else if (!token.value) {
    next('/login');
  } else if (layoutLeftRoutes.value.length === 0) {
    setAddRoute();
    next({ path: to.path, query: to.query });
  } else {
    next();
  }
});

// 路由加载后
router.afterEach(() => {
  NProgress.done();
});

export default router;
